<!--
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 14:41:20
 * @LastEditTime: 2023-11-01 13:02:20
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description:   :gridOps="gridOptions"
-->
<template>
  <el-dialog
    :title="'选择'"
    v-model:visible="visible"
    :width="browser.width"
    destroy-on-close
    draggable
    overflow
  >
    <el-container>
      <el-aside v-if="category" width="150px">
        <div :style="{ height: height + 'px' }">
          <sk-category
            :url="browser.categoryUrl"
            @select="categoryselect"
            :params="browser.categoryparams"
            :editable="false"
          ></sk-category>
        </div>
      </el-aside>
      <el-main style="height: 100%">
        <sc-VxeTable
          ref="xGrid1"
          :gridEvts="gridEvents"
          :gridOps="gridOps"
          :tablecode="browser.tablecode"
          :params="loadParam"
          :url="browser.url"
        >
        </sc-VxeTable>
      </el-main>
    </el-container>
    <template #footer>
      <el-button @click="$emit('close')">关 闭</el-button>
    </template>
    <component
      :is="componentDlg"
      v-if="componentDlg"
      v-model="componentOpen"
      ref="componentRef"
      @success="handleSuccess"
      @closed="componentOpen = false"
    ></component>
  </el-dialog>
</template>
<script>
import config from "@/config/autocomplete";
import { markRaw } from "vue";
import skCategory from "@/components/skCategory";
export default {
  components: { skCategory },
  emits: ["select", "close"],
  props: {
    name: null,
    params: null,
    single: { type: Boolean, default: false }, //单选，多选
    row: null,
  },
  created() {},
  watch: {
    params() {
      this.loadParam();
    },
  },
  mounted() {
    let params = this.loadParam();

    if (!this.isEmpty(this.browser, "vueDlg")) {
      this.browser.vueDlg.filter(v => {
        this.gridEvents[v.action] = param => {
          this.loaderDilog(v.url)
            .then(res => {
              this.componentDlg = markRaw(res.default);
              if (!this.isEmpty(v, "callback")) {
                this.$nextTick(() => {
                  v.callback(this.$refs.componentRef, param, this.row, params);
                });
              }
              this.componentOpen = true;
            })
            .catch(msg => {
              this.loaderDilog("common/empty").then(res => {
                this.componentDlg = markRaw(res.default);
                this.$nextTick(() => {
                  this.$refs.componentRef.setData(msg + "");
                });
                this.componentOpen = true;
              });
            });
        };
      });
    }
  },

  data() {
    return {
      gridEvents: {
        cellDblclick: ({ row }) => {
          if (this.single) this.select(row);
          else this.select([row]);
        },
        choose: param => {
          let rows = param.$grid.getCheckboxRecords();
          if (this.single) this.select(rows[0]);
          else this.select(rows);
        },
        choose_goon: param => {
          let rows = param.$grid.getCheckboxRecords();
          if (this.single) this.select(rows[0], false);
          else this.select(rows, false);
        },
      },
      browser: config[this.name].browser,
      gridOps: {},
      category: false,
      visible: false,
      componentOpen: false,
      componentDlg: null,
      vueDlg: [],
      height: 400,
    };
  },
  methods: {
    // loaderDilog: (url) => Promise.resolve(require(`@/views/${url}`).default),
    // loaderDilog: (url) => {
    //   return import(`@/views/${url}`);
    //   //  (resolve) => ;
    // },
    loadParam() {
      if (this.isEmpty(this.browser, "url")) {
        this.browser["url"] = config[this.name].url.cp();
      }
      if (this.isEmpty(this.browser, "width")) {
        this.browser["width"] = 400;
      }
      if (this.isEmpty(this.browser, "height")) {
        this.gridOps["height"] = 600;
      } else {
        this.gridOps["height"] = this.browser["height"];
      }
      this.height = this.browser["height"];
      if (!this.isEmpty(this.browser, "categoryUrl")) {
        this.category = true;
      }
      let defaultparams = null;
      let urlparams = [];
      if (typeof this.params === "function") defaultparams = this.params();
      else defaultparams = this.params;

      defaultparams =
        defaultparams instanceof Array ? defaultparams : [defaultparams ?? {}];
      defaultparams?.forEach(elm => {
        let urlparam = this.setRowValue(elm);

        if (JSON.stringify(urlparam) != "{}") urlparams.push(urlparam);
      });

      defaultparams =
        this.browser["params"] instanceof Array
          ? this.browser["params"]
          : [this.browser["params"] ?? {}];

      defaultparams?.forEach(elm => {
        let urlparam = this.setRowValue(elm);
        if (JSON.stringify(urlparam) != "{}") urlparams.push(urlparam);
      });

      return this.browser["params"] ?? [], urlparams;
    },
    setRowValue(elm) {
      let urlparam = {};
      for (let k in elm)
        if (this.row && this.row[elm[k]]) {
          urlparam[k] = this.row[elm[k]];
        } else if (elm[k]) urlparam[k] = elm[k];
      return urlparam;
    },

    loaderDilog: url => import(`@/views/${url}`),
    select: function (row, close = true) {
      this.$emit("select", row, close);
      this.visible = !close;
    },
    isEmpty(arrayJ, name) {
      if (typeof arrayJ[name] == "undefined") {
        return true;
      }
      return false;
    },
    categoryselect: function (data, ids) {
      this.$refs.xGrid1.search("category_id", ids, "in");
      this.handleSuccess();
    },
    refresh() {
      this.$refs.xGrid1.refresh();
    },
    handleSuccess() {
      this.refresh();
      this.componentOpen = false;
    },
  },
};
</script>
